<?php

use PHPMailer\PHPMailer\PHPMailer;
use think\File;

/**
 * 给树状菜单添加level并去掉没有子菜单的菜单项
 * @param  array   $data  [description]
 * @param  integer $root  [description]
 * @param  string  $child [description]
 * @param  string  $level [description]
 */
function memuLevelClear($data, $root = 1, $child = 'child', $level = 'level')
{
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            $data[$key]['selected'] = false;
            $data[$key]['level'] = $root;
            if (!empty($val[$child]) && is_array($val[$child])) {
                $data[$key][$child] = memuLevelClear($val[$child], $root + 1);
            } else if ($root < 3 && $data[$key]['menu_type'] == 1) {
                unset($data[$key]);
            }
            if (empty($data[$key][$child]) && ($data[$key]['level'] == 1) && ($data[$key]['menu_type'] == 1)) {
                unset($data[$key]);
            }
        }
        return array_values($data);
    }
    return array();
}

/**
 * [rulesDeal 给树状规则表处理成 module-controller-action ]
 * @AuthorHTL
 * @DateTime  2017-01-16T16:01:46+0800
 * @param     [array]                   $data [树状规则数组]
 * @return    [array]                         [返回数组]
 */
function rulesDeal($data)
{
    if (is_array($data)) {
        $ret = [];
        foreach ($data as $k1 => $v1) {
            $str1 = $v1['name'];
            if (is_array($v1['child'])) {
                foreach ($v1['child'] as $k2 => $v2) {
                    $str2 = $str1 . '-' . $v2['name'];
                    if (is_array($v2['child'])) {
                        foreach ($v2['child'] as $k3 => $v3) {
                            $str3 = $str2 . '-' . $v3['name'];
                            $ret[] = $str3;
                        }
                    } else {
                        $ret[] = $str2;
                    }
                }
            } else {
                $ret[] = $str1;
            }
        }
        return $ret;
    }
    return [];
}

/**
 * cookies加密函数
 * @param string 加密后字符串
 */
function encrypt($data, $key = 'kls8in1e')
{
    $prep_code = serialize($data);
    $block = mcrypt_get_block_size('des', 'ecb');
    if (($pad = $block - (strlen($prep_code) % $block)) < $block) {
        $prep_code .= str_repeat(chr($pad), $pad);
    }
    $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB);
    return base64_encode($encrypt);
}

/**
 * cookies 解密密函数
 * @param array 解密后数组
 */
function decrypt($str, $key = 'kls8in1e')
{
    $str = base64_decode($str);
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = ord($str[($len = strlen($str)) - 1]);
    if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) {
        $str = substr($str, 0, strlen($str) - $pad);
    }
    return unserialize($str);
}

/**
 * 储存单位转换
 * 参数
 * byte 字节数
 */
// function trans_byte($byte)
// {
//     $KB = 1024;
//     $MB = 1024 * $KB;
//     $GB = 1024 * $MB;
//     $TB = 1024 * $GB;
//     if ($byte < $KB) {
//         return $byte . "B";
//     } elseif ($byte < $MB) {
//         return round($byte / $KB, 2) . "KB";
//     } elseif ($byte < $GB) {
//         return round($byte / $MB, 2) . "MB";
//     } elseif ($byte < $TB) {
//         return round($byte / $GB, 2) . "GB";
//     } else {
//         return round($byte / $TB, 2) . "TB";
//     }
// }

/**
 * 上传文件
 */
function burstUpload($destination, $file)
{
    try {
        //throw new \Exception('move file fail');
        if (move_uploaded_file($_FILES['file']['tmp_name'], $destination . DS . $file . '.tmp' . $_POST['chunkNumber'])) {
            if ($_POST['chunkNumber'] == $_POST['totalChunks']) {
                $fp = fopen($destination . DS . $file, 'w');
                for ($i = 1; $i <= $_POST['totalChunks']; $i++) {
                    if (file_exists($destination . DS . $file . '.tmp' . $i)) {
                        fwrite($fp, file_get_contents($destination . DS . $file . '.tmp' . $i));
                        @unlink($destination . DS . $file . '.tmp' . $i);
                    } else {
                        continue;
                    }
                }
                fclose($fp);
                file_put_contents($destination . DS . pathinfo($file)['filename'] . '.md5', md5_file($destination . DS . $file));
                return true;
            }
            return false;
        } else {
            throw new \Exception('move file fail');
        }
    } catch (\Exception $e) {
        throw new \Exception('upload file fail : ' . $e->getMessage());
    }
}


/**
 * 发送邮箱
 * @param type $data 邮箱队列数据 包含邮箱地址 内容
 */
function sendEmail($data = [])
{
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host = 'smtp.mxhichina.com'; //SMTP服务器 以126邮箱为例子 
    $mail->Port = 465;  //邮件发送端口
    $mail->SMTPAuth = true;  //启用SMTP认证
    $mail->SMTPSecure = "ssl";   // 设置安全验证方式为ssl
    $mail->CharSet = "UTF-8"; //字符集
    $mail->Encoding = "base64"; //编码方式
    $mail->Username = 'asrupload@raisound.com';  //你的邮箱 
    $mail->Password = 'Rs86329312';  //你的密码 
    $mail->Subject = $data['title']; //邮件标题  
    $mail->From = 'asrupload@raisound.com';  //发件人地址（也就是你的邮箱）
    $mail->FromName = 'raisound';  //发件人姓名

    $mail->AddAddress($data['send_email']); //添加收件人（地址，昵称）
    $mail->IsHTML(true); //支持html格式内容
    $mail->Body = $data['content']; //邮件主体内容
    //发送成功就删除
    if (!$mail->Send()) {
        throw new Exception("Mailer Error: " . $mail->ErrorInfo);
    }      
    return true;
}


/**
 * 读取文件
 * @param $type 读取方式
 */
function cusReadFile($filePath, $type) {
    $str = file_get_contents($filePath);

    switch ($type) {
        case 0: // txt 每个词折行
            return explode(',', str_replace("\n", ',', $str));
            break;

        case 1: // xls,xlsx
            die(json_encode(['aaa' => $str]));
            break;
        default:
            return false;
            break;
    }
}

/**
 * 生成文件 | 并返回文件路径
 * @param $fileFolder 文件夹
 * @param $fileName 文件名 从根目录开始,结尾加/ 例如：/data/sensitive/
 * @param $suffix 后缀
 * @param $content 文件内容
 */
function generateFile($fileFolder, $fileName, $suffix, $content) {
    switch ($suffix) {
        case 'txt':
            $filePath = $fileFolder.$fileName.'.'.$suffix;
            $rootPath = ROOT_PATH.$filePath;

            // 创建文件
            $file = fopen($rootPath, "w+");

            // 填写文件内容
            fwrite($file, $content);
            fclose($file);

            // 返回
            return $filePath;
            break;
        
        default:
            return false;
            break;
    }
}